const express = require('express')
const router = express.Router()
const db = require('./modules/db')
const userController = require('./controllers/user')
const topicController = require('./controllers/topic')
const commentController = require('./controllers/comment')
const sessionController = require('./controllers/sesion')


// 校验登录状态
function checkLogin(req, res, next) {
    if (!req.session.user) {
        return res.status(401).json({
            error: '错误：用户不在状态,请登录'
        })
    }
    next()
}

// 检查用户话题和用户登录是否一致
async function checkUser(req, res, next) {

    try {
        const { id } = req.params
        const [userId] = await db.query(`SELECT * FROM topics WHERE id = ${id}`)

        if (userId.user_id !== req.session.user.id) {
            return res.status(402).json({
                err: '当前用户没有权限操作这条数据'
            })
        }
        next()
    } catch (err) {
        next(err)
    }
}

// 用户资源路由

router
    .get('/users', userController.list)
    .post('/users', userController.create)
    .patch('/users/:id', userController.update)
    .delete('/users/:id', userController.delete)


// 话题资源处理

router
    .get('/topics', topicController.list)
    .get('/topics/:id', topicController.once)
    .post('/topics', checkLogin, topicController.create)
    .patch('/topics/:id', checkLogin, checkUser, topicController.update)
    .delete('/topics/:id', checkLogin, checkUser, topicController.delete)


//评论区资源处理

router
    .get('/comments/:id', checkLogin, commentController.list)
    .post('/comments', checkLogin, commentController.create)
    .patch('/comments/:id', checkLogin, commentController.update)
    .delete('/comments/:id', checkLogin, commentController.delete)


//会话管理

router
    .get('/session', sessionController.get)
    .post('/session', sessionController.create)
    .patch('/session', sessionController.edit)
    .delete('/session', sessionController.delete)

module.exports = router